/*
  Klistrat ihop main.js med authentication.js
  Se authentication.js och main.js för kommentarer.
  authentication.js har några video-källor.
  //-----------
  Socket.IO's `listen()` method expects an `http.Server` instance
  as its first parameter. Are you migrating from Express 2.x to 3.x?
  If so, check out the "Socket.IO compatibility" section at:
  https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x

  //-----------
*/
var express = require('express');
var http = require('http');
var app = express();
var UserModel = require('./User').UserModel;
var db = require('./User').db;
var fs = require('fs');
var sIOLayer = require('./socketIO-layer.js');

var RedisStore = require('connect-redis')(express);
var secret_salt_hash = 'secret salt hash';
app.use(express.cookieParser());
app.use(express.session( {store: new RedisStore, secret: secret_salt_hash}));
app.use(express.bodyParser());

// 'middleware' concept in Express.
// Requires the user to be logged in before passing on to the next route
var requireLogin = function(req, res, next) {
    if (req.session.user)    next()

    // after logging in, redirects you to 'req.url'
    else res.redirect('/login?redir='+req.url); 
}

var sendfile = function(req, res, filename) {
    fs.readFile(__dirname + filename,
                function (err, data) {
                    if (err) {
                        res.writeHead(500);
                        console.log('Error loading ' + filename);
                        res.end('Error loading ' + filename);
                    }
                    else {
                        res.writeHead(200);
                        res.end(data);
                        console.log('sucess loading ' + filename);
                    }
                });
};
    

app.get('/', requireLogin, function(req, res) {
    sendfile(req, res, '/index.html');
});

app.get('/index.html', requireLogin, function(req, res) {
    sendfile(req, res, '/index.html');
});

app.get('/index_js.js', requireLogin, function(req, res) {
    sendfile(req, res, '/index_js.js');
});


app.get('/login', function(req, res) {
    sendfile(req, res, '/login.html');
});

app.get('/style.css', function(req, res) {
    sendfile(req, res, '/style.css');
});

app.post('/login', function(req, res) {
    console.log('trying to log in, name = ' + req.body.name + ', pwd = ' + req.body.password);
    //db.once('open', function callback () {
    UserModel.findOne({name: req.body.name}, function(err, result) {
        console.log("matches: " + result);
        if (result === null) {
            console.log('nope...');
            res.send('No such user!');
        }
        else if (result.password === req.body.password) {
            console.log('Yea!!!');
            req.session.user = result;
            res.send('Logged in!!!');
            res.redirect('/');
        }
    });
});

var server = http.createServer(app);
server.listen(12345);
sIOLayer.serverToSocket(server);
